<template>
  <div class="song-lyric" ref="songLyric" v-if="lyric ? lyric : ''">
      <p class="every-lyric" ref="sing"
      :class="{'active':allKeys[index+1] > currentTime && currentTime > allKeys[index]}"
      v-for="(item,key,index) in lyric"
      :key="index"
      >
      <span >{{item}}-{{ pushScroll(index) }}</span>
      
      </p>
  </div>
</template>

<script>
import {mapState,mapMutations,mapAction } from 'vuex'

export default {
  data() {
    return {
      lyric:'',
      allKeys:[],
    }
  },
  computed: {
    ...mapState(['songUrl','songCover','songLriycs','currentTime'])
  },
  methods: {
    filterLyric(lyc) {
      if(!lyc) return 
      const lyric = lyc.split("\n");
      var reg = /\[\d*:\d*(\.|:)\d*]/g;
      // 创建一个存放歌词的对象：键为时间，值为歌词
      var lyricObj = {}
      for(let i = 0; i < lyric.length; i++) {
        //获得一个只要时间戳的数组
        var timeRegArr = lyric[i].match(reg);
        //不符合时间戳格式的不匹配;
        if(!timeRegArr) continue;
        //获取歌词
        var content = lyric[i].replace(timeRegArr,"")
        // console.log(content)
        var t = timeRegArr[0];
        var min = parseInt(t.match(/\[\d*/i).toString().slice(1));
        var sec = parseInt(t.match(/\:\d*/i).toString().slice(1));
        var time = min * 60 + sec;
        lyricObj[time] = content;
      }
      this.getAllKeys(lyricObj)
      return lyricObj
    },

    //提取歌词对象中所有key与现在播放的事件作比较
    getAllKeys(lyricObj) {
      console.log(lyricObj)
      for(let key in lyricObj) {
          this.allKeys.push(key);
      }
    },

    // 控制元素滚动条
    pushScroll(index) {
        // 此方法可以把内容滚动指定的像素数，第一个参数是x方向，第二个参数是y方向
        // if(this.allKeys[index+1] > this.currentTime && this.currentTime > this.allKeys[index]) {
        //     this.$refs.songLyric.scrollTop = -160 + (40 * index);
        // }
    },
  },
  mounted() {
    console.log(this.$refs.sing)
    this.lyric = this.filterLyric(this.songLriycs)
  },
}
</script>

<style lang="less" scoped>
.song-lyric {
  display: flex;
  flex: 1;
  flex-direction: column;
  height: 367px;
  overflow: hidden;
  color: rgb(185, 185, 185);
  font-size: 1.2em;
  .every-lyric {
    height: 20px;
    line-height: 20px;
    margin: 10px auto;
    flex: 1;
    text-align: center;
  }
}
.active {
  color: rgb(157, 97, 212)
}
</style>>